var http = require("http");
var url = require("url");
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://127.0.0.1:27017/monografia", function(err, db) {
	http.createServer(function(request, response) {
		var path = url.parse(request.url, true).path;
		if(7==path.length) {		
			var col = db.collection('url');
			col.findOne({hash:path},function(err,result) {
				if(!err && result) {
					var sUrl = 'http://'+result['url'];
					response.writeHead (301, {'Location': sUrl});
				}
				else {
					response.writeHead(404);
				}
				db.close();
				response.end();
			});	
		}
		else {
			response.writeHead(404);
			response.end();
		}
	}).listen(80);
	console.log("Server Running 80...");
})
